package com.xiaozhengkeji.springcloud.ezcloud.servicebus;

import com.google.gson.Gson;
import com.xiaozhengkeji.springcloud.ezcloud.common.core.base.entitys.user.SystemUserEntity;
import com.xiaozhengkeji.springcloud.ezcloud.common.core.base.services.user.SystemUserEntityService;
import com.xiaozhengkeji.springcloud.ezcloud.common.core.events.user.UserRegisterEvent;
import com.xiaozhengkeji.springcloud.ezcloud.common.core.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

@Service("UserServiceBus")
@Slf4j
public class UserServiceBus {

    ApplicationEventPublisher applicationEventPublisher;
    SystemUserEntityService systemUserEntityService;

    private final static List<String> Def_Role = new LinkedList<>();
    private final static List<String> Def_Permissions = new LinkedList<>();

    @Autowired
    public UserServiceBus(ApplicationEventPublisher applicationEventPublisher, SystemUserEntityService systemUserEntityService) {
        this.applicationEventPublisher = applicationEventPublisher;
        this.systemUserEntityService = systemUserEntityService;
        Def_Role.add("def");
        Def_Permissions.add("user:def");
    }

    /**
     * 注册一个用户
     *
     * return {
     *     -1: 用户已经存在
     *     0:  注册成功
     *     -2: 注册失败数据库出错
     * }
     */
    public Integer registeredUser(String username,String password) {
        if (systemUserEntityService.queryByUsername(username).size() > 0) return -1;
        SystemUserEntity temp_SystemUserEntity = new SystemUserEntity();
        temp_SystemUserEntity.setUsername(username);
        //对密码进行 hash
        temp_SystemUserEntity.setPassword(UserUtils.userPasswordHash(password));
        //temp_SystemUserEntity.setMailbox("待绑定");
        temp_SystemUserEntity.setStatus(1);
        //temp_SystemUserEntity.setPhone("待绑定");
        temp_SystemUserEntity.setRegTime(LocalDateTime.now());
        temp_SystemUserEntity.setRole(new Gson().toJson(Def_Role));//角色
        temp_SystemUserEntity.setPermissions(new Gson().toJson(Def_Permissions));//权限
        if (systemUserEntityService.insert(temp_SystemUserEntity) > 0){
            applicationEventPublisher.publishEvent(new UserRegisterEvent(this,username));
            return 0;
        }
        return -2;
    }



}
